% By: Carmen Guerra Garcia
% Date: March 27th 2019

%Description: This script reads a raw video file (.mov), extracts frames
%from it, determines corona as the region of maximum
%intensity and tracks total intensity 

 clear all
 close all
 clc

workingDir = tempname;
mkdir(workingDir);
mkdir(workingDir,'images');

filenames= {'03282019_wp3_PS13'};
figure(1)

for k=1

data = VideoReader([filenames{k} , '.mov']);

NN = data.NumberOfFrames;

for ii = 895:50:11500
    img = read(data,ii)-read(data,11800);
    imwrite(img,fullfile(workingDir,'images',sprintf('img%d.jpg',ii)));
end
imageNames = dir(fullfile(workingDir,'images','*.jpg'));
imageNames = {imageNames.name}';

imageStrings = regexp([imageNames{:}],'(\d*)','match');
imageNumbers = str2double(imageStrings);
[~,sortedIndices] = sort(imageNumbers);
sortedImageNames = imageNames(sortedIndices);

for ii=1:length(sortedImageNames)
img = imread(fullfile(workingDir,'images',sortedImageNames{ii}));

Irr(ii) = sum(sum(img(580:630,600:1300,1),'omitnan'));

end

Nframe = [895:50:11500];

tt = Nframe./29.97./60; %min

plot(tt,Irr./max(Irr))

grid on

hold on

xlabel('Time [s]')
ylabel('Relative intensity [au]')

TU = [0.4978 0.9 1.82 2.4 2.92 3.37 3.84 4.34 5.25 ];
U  = [0 10 20 25 30 35 40 45 50]';
Utxt = num2str(U);


IU(1:length(TU)) = nan;
for kk=1:length(TU)
IU(kk) = interp1(tt,Irr./max(Irr),TU(kk));
end

frame_n(1:length(TU)) = nan;
for kk=1:length(TU)
frame_n(kk)= interp1(tt,[1:length(sortedImageNames)],TU(kk),'nearest');
end

plot(TU,IU,'ro')
for kk=1:length(TU)
text(TU(kk)+0.1, IU(kk)+0.05, ['U=' Utxt(kk,1:2) 'm/s'] )
end



end

figure(2)
subplot(5,2,[1,2],'Position',[0.08 0.84 0.8 0.16])
img = imread(fullfile(workingDir,'images',sortedImageNames{frame_n(1)}));
imagesc(imcrop(img,[120 380 1600 450]));
axis equal
axis off
hold on
for i=2:9
    if i==2
    corner = 0.68; 
    side = 0.1;
    elseif i==3
    corner = 0.68;
    side = 0.45;
    elseif i ==4 
    corner = 0.52;
    side = 0.1;
    elseif i ==5 
    corner = 0.52;
    side = 0.45;
    elseif i ==6
    corner = 0.36;
    side = 0.1;
    elseif i ==7 
    corner = 0.36;
    side = 0.45;
    elseif i ==8
    corner = 0.2;
    side = 0.1;
    elseif i ==9
    corner = 0.2;
    side = 0.45;    
    end          
subplot(5,2,i+1,'Position',[side corner 0.42 0.16])
hold on
img = imread(fullfile(workingDir,'images',sortedImageNames{frame_n(i)}));
imagesc(imcrop(img,[120 380 1600 450]));
axis equal
axis off;
end












